package com.et.u1.vm.home;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;

import androidx.lifecycle.ViewModel;

import com.bumptech.glide.Glide;
import com.et.u1.R;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class HomeViewModel extends ViewModel {
    // TODO: Implement the ViewModel
    private void initBanner(Banner mBanner) {
        int[] imageResourceID = new int[]{R.mipmap.index, R.mipmap.index, R.mipmap.index, R.mipmap.index};
        List<Integer> imgeList = new ArrayList<>();

        for (int j : imageResourceID) {
            imgeList.add(j);
            mBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    Glide.with(context).load(path).into(imageView);
                }
            });
            mBanner.setBannerAnimation(Transformer.RotateDown);
            mBanner.setImages(imgeList);
            mBanner.setBannerStyle(BannerConfig.NOT_INDICATOR);
            mBanner.setDelayTime(3_000);
            mBanner.setOnBannerListener(position -> {
            });
            mBanner.start();
        }
    }

    protected void initAdvView(Context context, VideoView videoView, Banner mBanner) {
        ContentResolver contentResolver = Objects.requireNonNull(context).getContentResolver();
        String[] projection = new String[]{MediaStore.Video.Media.DISPLAY_NAME};
        Cursor cursor = contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
        cursor.moveToFirst();
        String videoUrl = null;
        for (int counter = 0; counter < cursor.getCount(); counter++) {
            videoUrl = Environment.getExternalStorageDirectory().getPath() + "/" + cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
            cursor.moveToNext();
        }
        cursor.close();
        if (videoUrl != null) {
            //设置视频控制器
            MediaController controller = new MediaController(context);

            controller.hide();

            videoView.setMediaController(controller);
            //播放完成回调
            videoView.setOnCompletionListener(mp -> videoView.start());
            //设置视频路径
            videoView.setVideoPath(videoUrl);
            //开始播放视频
            videoView.start();
        } else {
            videoView.setVisibility(View.GONE);
            initBanner(mBanner);
        }
    }
}